package com.berchen.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class ShiroController {

//    @RequestMapping("login")
    public String login(Model model){

        Subject subject = SecurityUtils.getSubject();
        subject.logout();

        // 判断是否登录过，
        if(!subject.isAuthenticated()){
            UsernamePasswordToken token = new UsernamePasswordToken("username", "password");
            try{
                subject.login(token);
            }
            catch (LockedAccountException e) {
                //e.printStackTrace();
                // 登录失败，会抛出各种异常
                model.addAttribute("errorMessage", "账号被锁定");
                return "login"; // 去到登录页面
            } catch (UnknownAccountException e) {
                //e.printStackTrace();
                // 登录失败，会抛出各种异常
                model.addAttribute("errorMessage", "账号错误");
                return "login"; // 去到登录页面
            } catch (IncorrectCredentialsException e) {
                //e.printStackTrace();
                // 登录失败，会抛出各种异常
                model.addAttribute("errorMessage", "密码错误");
                return "login"; // 去到登录页面
            } catch (AuthenticationException e) {
                e.printStackTrace();
                // 登录失败，会抛出各种异常
                model.addAttribute("errorMessage", "认证失败");
                return "login"; // 去到登录页面
            }
        }
        // 登录成功
        return "redirect:/success";
    }
    /**
     * 没有权限去的页面
     *
     * @return
     */
    @RequestMapping("/noPermission")
    public String noPermission() {

        return "noPermission";
    }

}
